package com.gitee.jjnnzb.designpatterndemo.handler.impl;

import com.gitee.jjnnzb.designpatterndemo.handler.UrlHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Jjn
 * @since 2023/3/6 18:12
 */
@Service
@Slf4j
@Order(value = 10)
@RequiredArgsConstructor
public class WeiboApiHandler implements UrlHandler {
    
    private static final Pattern MID_WEB_PATTERN = Pattern.compile("weibo.*/(\\d+)/(\\w{9}).*");
    private static final Pattern MID_MOBILE_LONG_MID_PATTERN = Pattern.compile("m\\.weibo\\.cn/status/(\\d{16}).*");
    private static final Pattern MID_MOBILE_STRING_MID_PATTERN = Pattern.compile("m\\.weibo\\.cn/status/(\\w{9}).*");
    private static final List<Pattern> MID_PATTERNS = List.of(MID_WEB_PATTERN, MID_MOBILE_LONG_MID_PATTERN, MID_MOBILE_STRING_MID_PATTERN);
    
    @Override
    public boolean apply(String url) {
        if (!StringUtils.hasText(url)) {
            return false;
        }
        for (Pattern pattern : MID_PATTERNS) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.find()) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public void handle(String url) {
        if (log.isInfoEnabled()) {
            log.info("url:{}是微博链接,执行微博接口处理策略", url);
        }
    }
}
